package com.education.platform.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.education.platform.common.ResultCode;
import com.education.platform.dto.parent.ParentQueryDTO;
import com.education.platform.entity.User;
import com.education.platform.entity.UserProfile;
import com.education.platform.exception.BusinessException;
import com.education.platform.mapper.UserMapper;
import com.education.platform.mapper.UserProfileMapper;
import com.education.platform.service.ParentService;
import com.education.platform.vo.parent.ParentVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 家长服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ParentServiceImpl implements ParentService {

    private final UserMapper userMapper;
    private final UserProfileMapper userProfileMapper;

    @Override
    public Map<String, Object> adminGetParents(ParentQueryDTO queryDTO) {
        Page<User> page = new Page<>(queryDTO.getPage(), queryDTO.getSize());

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(User::getRoles, "PARENT");

        // 关键词查询
        if (StrUtil.isNotBlank(queryDTO.getKeyword())) {
            wrapper.and(w -> w
                .like(User::getUsername, queryDTO.getKeyword())
                .or().like(User::getMobile, queryDTO.getKeyword())
            );
        }

        // 状态查询
        if (StrUtil.isNotBlank(queryDTO.getStatus())) {
            wrapper.eq(User::getStatus, queryDTO.getStatus());
        }

        wrapper.orderByDesc(User::getCreatedAt);

        Page<User> userPage = userMapper.selectPage(page, wrapper);
        List<User> users = userPage.getRecords();

        if (users.isEmpty()) {
            Map<String, Object> result = new HashMap<>();
            result.put("list", new ArrayList<>());
            result.put("total", 0);
            return result;
        }

        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());

        Map<Long, UserProfile> profileMap = new HashMap<>();
        List<UserProfile> profiles = userProfileMapper.selectList(
            new LambdaQueryWrapper<UserProfile>().in(UserProfile::getUserId, userIds)
        );
        profiles.forEach(profile -> profileMap.put(profile.getUserId(), profile));

        List<ParentVO> parentList = users.stream().map(user -> {
            ParentVO vo = new ParentVO();
            UserProfile profile = profileMap.get(user.getId());

            vo.setId(user.getId());
            vo.setUsername(user.getUsername());
            vo.setMobile(user.getMobile());
            vo.setEmail(user.getEmail());
            vo.setAvatarUrl(user.getAvatarUrl());
            vo.setStatus(user.getStatus());
            vo.setCreatedAt(user.getCreatedAt());

            if (profile != null) {
                vo.setRealName(profile.getRealName());
            }

            // TODO: 从订单表、需求表统计数据
            vo.setDemandCount(0);
            vo.setOrderCount(0);
            vo.setFavoriteCount(0);
            vo.setReviewCount(0);

            return vo;
        }).collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("list", parentList);
        result.put("total", userPage.getTotal());
        result.put("page", queryDTO.getPage());
        result.put("size", queryDTO.getSize());

        return result;
    }

    @Override
    public ParentVO adminGetParentDetail(Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_FOUND);
        }

        if (!user.getRoles().contains("PARENT")) {
            throw new BusinessException("该用户不是家长");
        }

        UserProfile profile = userProfileMapper.selectOne(
            new LambdaQueryWrapper<UserProfile>().eq(UserProfile::getUserId, id)
        );

        ParentVO vo = new ParentVO();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setMobile(user.getMobile());
        vo.setEmail(user.getEmail());
        vo.setAvatarUrl(user.getAvatarUrl());
        vo.setStatus(user.getStatus());
        vo.setCreatedAt(user.getCreatedAt());

        if (profile != null) {
            vo.setRealName(profile.getRealName());
        }

        // TODO: 统计数据
        vo.setDemandCount(0);
        vo.setOrderCount(0);
        vo.setFavoriteCount(0);
        vo.setReviewCount(0);

        return vo;
    }

    @Override
    @Transactional
    public void adminUpdateParentStatus(Long id, String status) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_FOUND);
        }

        if (!user.getRoles().contains("PARENT")) {
            throw new BusinessException("该用户不是家长");
        }

        user.setStatus(status);
        userMapper.updateById(user);

        log.info("管理员更新家长状态: userId={}, status={}", id, status);
    }
}

